// import { allDirection } from '@/api/dict.js'
import { mapMutations, mapActions } from 'vuex'
import { buildDictTree } from '../libs/utils'
// 查询字典项的方法混入
export default {
  data() {
    return {
      dictData: {}
    }
  },
  computed: {},
  methods: {
    ...mapMutations('common', ['setDictData']),
    ...mapActions('common', ['getAllDirection']), //store避免同一时间重复请求
    async getDictByName(type, cache) {
      if (!(cache && this.$store.state.common.dictData[type])) {
        let data = await this.getAllDirection(type)
        // console.log('dictMixin方法请求返回',data)
        if (data) {
          let dictData = {
            data,
            treeData: buildDictTree(data)
          }
          this.setDictData({ type, dictData })
        }
      }
      let dictData = this.$store.state.common.dictData[type]
      this.$set(this.dictData, type, dictData)
      return dictData
    },
    // 获取层级数据
    getLevelData(data = [], level = 0) {
      return data.filter((item) => item.level === level)
    },
    getTreeData: buildDictTree,
    // 根据id获取字典详情
    getDictDetailById(dictid = '', data = []) {
      let dict = data.find((item) => item.dictid === dictid)
      return dict
    },
    //根据id获取名称
    getNameById(dictid = '', data = []) {
      let dict = data.find((item) => item.dictid === dictid)
      return dict ? dict.dictname : '未知类型'
    },
    //获取字典父级详情
    getDictParent(dictid = '', data = []) {
      let type = data.find((dict) => dict.dictid == dictid)
      let direction = ''
      if (type) {
        direction = data.find((dict) => dict.dictid == type.parentid)
      }
      return direction
    },
    // 获取字典所有父级
    getDictAllParent(id = '', data = [], parents = [], parentIds = []) {
      if (!id) {
        return
      }
      let { dictid, dictname, parentid } = this.getDictDetailById(id, data)
      parents.unshift(dictname)
      parentIds.unshift(dictid)
      if (parentid) {
        return this.getDictAllParent(parentid, data, parents, parentIds)
      } else {
        return {
          parents,
          parentIds
        }
      }
    },
    //根据id,分隔符显示字典名称
    handleDictSepShow(val = '', data = [], separate = '/') {
      if (!val) {
        return '-'
      }
      if (Array.isArray(val)) {
        return val.map((item) => this.getNameById(item, data)).join(separate)
      }
      let { parents } = this.getDictAllParent(val, data)
      return parents.join(separate)
    },
    getDictChildren(dictid = '', data = [], parentDictList) {
      if (dictid == 'All') {
        //二级有效
        if (!parentDictList) {
          return data.filter((dict) => dict.parentid)
        } else {
          return data.filter((dict) =>
            parentDictList.map((item) => item.dictid).includes(dict.parentid)
          )
        }
      } else {
        return data.filter((dict) => dict.parentid == dictid)
      }
    }
  }
}
